<?php

namespace app\api\validate;

use think\Container;
use think\Db;
use think\exception\ClassNotFoundException;

/**
 * 验证模型是否存在
 * Trait ValidateModelExist
 * @package app\api\validate
 */
trait ValidateModelExist
{

    /**
     * @param $value
     * @param $rule 验证规则格式：数据表,主键名
     * @param $data
     * @param $field
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function exist($value, $rule, $data, $field)
    {
        if (is_string($rule)) {
            $rule = explode(',', $rule);
        }

        if (false !== strpos($rule[0], '\\')) {
            // 指定模型类
            $db = new $rule[0];
        } else {
            try {
                $db = Container::get('app')->model($rule[0]);
            } catch (ClassNotFoundException $e) {
                $db = Db::name($rule[0]);
            }
        }

        $pk = !empty($rule[1]) ? $rule[1] : $db->getPk();
        if ($db->field($pk)->find($value)) {
            return true;
        }
        return false;
    }
}
